package myauctioneer;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.stringtemplate.v4.ST;

public final class UserServlet extends DefaultServlet
{
	/**
	 * Show user account info.
	 */
	public void indexAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		ST rootTpl = this.app.getTemplate("root");
//CHANGE TO DEDICATED FUNCTION ... START		
		/**
		 * Check if logged in as customer,
		 * if YES, don't allow to create new customer
		 */
		Customer customer = new Customer(this.app);
		customer.load(request.getSession());

		boolean isLoggedIn=false;
		try {
			isLoggedIn=customer.isLoggedIn(request.getSession());
		}
		catch (Exception e /*ServletException se*/) {
			rootTpl.add("msg", e.toString());
		}
		if (!isLoggedIn) rootTpl.add("login","");			
//CHANGE TO DEDICATED FUNCTION ... END		
		ST tpl = this.app.getTemplate("account");

//HERE RE-	Customer customer = new Customer(this.app);
//HERE RE-	customer.load(request.getSession());

		rootTpl.add("title", "My account (UserServlet)");

		tpl.add("customer", customer);
		rootTpl.add("content", tpl);

		response.getWriter().println(rootTpl.render());
	}

	/**
	 * Logout action.
	 */
	public void logoutAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		/**
		 * Check if logged in as customer,
		 * if YES, LOGOUT
		 */
		Customer customer = new Customer(this.app);
		customer.load(request.getSession());

		try {
			if(customer.isLoggedIn(request.getSession()))
				request.getSession().invalidate();

		}
		catch (Exception e /*ServletException se*/) {
//OPEN			rootTpl.add("msg", e.toString());
		}
		//
		response.sendRedirect(app.getBaseUrl() + "/");
		return;
	}
	
	/**
	 * Login action.
	 */
	public void loginAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		Customer customer = new Customer(this.app);

		boolean loginDone = false;
		ST rootTpl = this.app.getTemplate("root");
//HERE RE-
		rootTpl.add("login","Einloggen");
//		
		ST tpl = this.app.getTemplate("login");

		/**
		 * Check login post
		 */
		if(request.getParameter("email") != null) {
			customer.loadByEmail(request.getParameter("email"));

			if(customer.getId() > 0 && customer.getPassword()
				.equals(request.getParameter("password")))
			{
				try {
					customer.setLoggedIn(request.getSession());
				}
				catch(Exception e) {
					throw new ServletException(e.toString(), e);
				}
				loginDone = true;
			}
			else {
				rootTpl.add("msg", "Login error: Email or Password not valid.");
			}
		}
		else {
			customer.load(request.getSession());

			// Session is valid, so no login needed?
			if(customer.getId() > 0)
				loginDone = true;
		}

		if(loginDone) {
			/**
			 * Todo: set a message in session to show on next page.
			 * - You are logged in.
			 * - Maybe redirect to referrer url
			 */
			response.sendRedirect(app.getBaseUrl() + "/user/");
			return;
		}

		rootTpl.add("title", "Login (UserServlet)");
		tpl.add("customer", customer);
		rootTpl.add("content", tpl);

		response.getWriter().println(rootTpl.render());
	}

	/**
	 * Register action.
	 */
	public void registerAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		ST rootTpl = this.app.getTemplate("root");

//CHANGE TO DEDICATED FUNCTION ... START		
		/**
		 * Check if logged in as customer,
		 * if YES, don't allow to create new customer
		 */
		Customer customer = new Customer(this.app);
		customer.load(request.getSession());

		boolean isLoggedIn=false;
		try {
			isLoggedIn=customer.isLoggedIn(request.getSession());
		}
		catch (Exception e /*ServletException se*/) {
			rootTpl.add("msg", e.toString());
		}
		if (!isLoggedIn) rootTpl.add("login","");			
//CHANGE TO DEDICATED FUNCTION ... END		
		
		if (isLoggedIn)
			rootTpl.add("msg", "Customer " + customer.getName() + " already logged in.<br />\n"+
				"Can't create new customer while logged in.");
		//unsauber ... 'isLoggedIn' kann 'false' sein ...?
		else {
			ST tpl = this.app.getTemplate("register");
			/**
			 * Check login post
			 */
			if(request.getParameter("register_button") != null) {
				
				//validate input ...!
				try {
					customer=new Customer(this.app).register(request);
					rootTpl.add("msg", "Registered " + customer.getName() + " as new user.");
					
					//add only if ... ok
					tpl.add("customer", customer);
//CLEAR CODE ABOVE PARTIALLY ... PENDING
//NO					response.sendRedirect(app.getBaseUrl() + "/hello/");
//???					return;				
				}
				catch (ServletException se) {
					rootTpl.add("msg", se.toString());
				}
			}
			rootTpl.add("content", tpl);		
		}

		rootTpl.add("title", "Registration (UserServlet)");
		
		response.getWriter().println(rootTpl.render());
	}
}
